package com.xr.blackhoole.rabbit.factory;

import com.xr.blackhoole.mvc.context.BlackholeContext;
import com.xr.blackhoole.mvc.context.BlackholeContextHolder;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;

public class BlackholeSimpleRabbitListenerContainerFactory extends SimpleRabbitListenerContainerFactory {


    @Override
    protected SimpleMessageListenerContainer createContainerInstance() {
        SimpleMessageListenerContainer simpleMessageListenerContainer = new SimpleMessageListenerContainer();
        simpleMessageListenerContainer.setAfterReceivePostProcessors(message -> {
            //防止线程复用
            BlackholeContextHolder.invalidContext();

            //获取消息属性标识
            String blackholeRequestContext = message
                    .getMessageProperties()
                    .getHeader(BlackholeContextHolder.BLACKHOLE_REQUEST_MARK);
            
            if (StringUtils.isNotEmpty(blackholeRequestContext)) {
                BlackholeContextHolder.setContext(blackholeRequestContext);
            }
            return message;
        });
        return simpleMessageListenerContainer;
    }
}
